package org.example.leetcode.core.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.example.leetcode.common.domain.SysUser;
import org.example.leetcode.common.utils.UserInfo;
import org.example.leetcode.core.utils.CommonUtils;
import org.example.leetcode.core.utils.RedisUtils;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author topto
 */
@Component
@Aspect
@Slf4j
public class QuestionOnClickAop {
    @Resource
    RedisUtils redisUtils;
    @Resource
    TaskExecutor taskExecutor;
    public static final String CLICK="click";

    @Pointcut("execution(* org.example.leetcode.core.service.TQuestionService.getQuestionInfo(..))")
    public void pointCut(){}

    @After("pointCut()")
    public void execute(JoinPoint joinPoint){
        try {
            Object[] args = joinPoint.getArgs();
            String titleSlug= (String) args[0];
            SysUser userInfo = UserInfo.getUserInfo();
            if(userInfo==null){
                return;
            }
            String phone = userInfo.getPhone();
            String key="click::"+phone+"::"+titleSlug;
            String currentDate = CommonUtils.getCurrentDate();
            String hotKey=RedisUtils.HOT+currentDate;
            taskExecutor.execute(()->{
                //记录每日一题
                redisUtils.setZset(hotKey,titleSlug,1L, TimeUnit.DAYS);
                //用于xxl记录题目点击次数，用户对类型的点击次数
                redisUtils.increment(key,60*60*1L);
            });
        } catch (Throwable e) {
            log.info("当前用户未登录，无需记录点击次数");
        }
    }
}
